package com.nd.service.wx;


import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nd.Utils.OrderUtils;
import com.nd.Utils.WhatOption;
import com.nd.Utils.WhatStatus;
import com.nd.dao.*;
import com.nd.pojo.bean.*;
import com.nd.pojo.bo.wx.CartCheckOutBo;
import com.nd.pojo.bo.wx.OrderCommentBO;
import com.nd.pojo.bo.wx.OrderSubmitBo;
import com.nd.pojo.vo.wx.CartCheckoutVo;
import com.nd.pojo.vo.wx.OrderActionBO;
import com.nd.pojo.vo.wx.WxOrderDetailVO;
import com.nd.pojo.vo.wx.WxOrderListVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: wx
 * @author: Aaron
 * @create: 2021-06-07 14:52
 **/
@Service
public class WxOrderServiceImpl implements WxOrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CartService cartService;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Override
    public WxOrderListVO orderList(Integer showType, Integer page, Integer size) {

        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        Integer id = user.getId();

        WxOrderListVO wxOrderListVO = new WxOrderListVO();

            PageHelper.startPage(page,size);
            OrderExample orderExample = new OrderExample();
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andUserIdEqualTo(id);
            criteria.andDeletedEqualTo(false);
            if (showType == 1) criteria.andOrderStatusEqualTo((short)101);
            if (showType == 2) criteria.andOrderStatusEqualTo((short)201);
            if (showType == 3) criteria.andOrderStatusEqualTo((short)301);
            List<Short> list = new ArrayList<>();
            list.add((short)401);
            list.add((short)402);
            if (showType == 4) criteria.andOrderStatusIn(list).andCommentsEqualTo((short)0);

            List<Order> orderList = orderMapper.selectByExample(orderExample);
            PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);
            long total = orderPageInfo.getTotal();
            wxOrderListVO.setTotalPages(total);
            wxOrderListVO.setCount(orderList.size());
            List<WxOrderListVO.Orders> ordersList = new ArrayList<>();
            for (Order order : orderList) {
                boolean groupIn = false;
                //判断是否拼团
                BigDecimal bigDecimal = new BigDecimal(0);
                if (order.getGrouponPrice().compareTo(bigDecimal) == 1) groupIn = true;
                OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
                OrderGoodsExample.Criteria criteriaOrderGoods = orderGoodsExample.createCriteria();
                criteriaOrderGoods.andOrderIdEqualTo(order.getId());
                List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
                List<WxOrderListVO.Goods> goodsList = new ArrayList<>();
                for (OrderGoods orderGoods : orderGoodsList) {
                    WxOrderListVO.Goods goods = WxOrderListVO.Goods.builder().number(orderGoods.getNumber()).picUrl(orderGoods.getPicUrl()).id(orderGoods.getId()).goodsName(orderGoods.getGoodsName()).build();
                    goodsList.add(goods);
                }
                WxOrderListVO.Orders orders = WxOrderListVO.Orders.builder().orderStatusText(new WhatStatus(order.getOrderStatus()).getOrderStatusText()).isGroupin(groupIn).orderSn(order.getOrderSn()).actualPrice(order.getActualPrice()).goodsList(goodsList).id(order.getId()).handleOption(new WhatOption(order.getOrderStatus(), order.getComments())).build();
                ordersList.add(orders);
            }
        wxOrderListVO.setData(ordersList);

        return wxOrderListVO;
    }

    @Override
    public WxOrderDetailVO orderDetail(Integer orderId) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();

        WxOrderDetailVO wxOrderDetailVO = new WxOrderDetailVO();

        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        List<Order> orderList = orderMapper.selectByExample(orderExample);

        boolean groupIn = false;
        if (orderList.get(0).getGrouponPrice().compareTo(new BigDecimal(0)) == 1) groupIn = true;

        WxOrderDetailVO.InfoChild infoChild = WxOrderDetailVO.InfoChild.builder()
                .consignee(user.getNickname())
                .expCode(orderList.get(0).getShipChannel())
                .expNo(orderList.get(0).getShipSn())
                .address(orderList.get(0).getAddress())
                .addTime(orderList.get(0).getAddTime())
                .orderSn(orderList.get(0).getOrderSn())
                .actualPrice(orderList.get(0).getActualPrice())
                .mobile(orderList.get(0).getMobile())
                .orderStatusText(new WhatStatus(orderList.get(0).getOrderStatus()).getOrderStatusText())
                .goodsPrice(orderList.get(0).getGoodsPrice())
                .couponPrice(orderList.get(0).getCouponPrice())
                .id(orderList.get(0).getId())
                .freightPrice(orderList.get(0).getFreightPrice())
                //是否拼团
                .isGroupin(groupIn)
                .handleOption(new WhatOption(orderList.get(0).getOrderStatus(), orderList.get(0).getComments())).build();

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteriaOrderGoods = orderGoodsExample.createCriteria();
        criteriaOrderGoods.andOrderIdEqualTo(orderList.get(0).getId());
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);

        wxOrderDetailVO.setOrderInfo(infoChild);
        wxOrderDetailVO.setOrderGoods(orderGoodsList);
        return wxOrderDetailVO;
    }

    @Override
    public void orderCancel(OrderActionBO orderId) {
        orderMapper.orderCancel(orderId.getOrderId());

    }

    @Override
    public void orderWxRefund(OrderActionBO orderId) {
        orderMapper.orderWxRefund(orderId);
    }

    @Override
    public void orderWxDelete(OrderActionBO orderId) {
        orderMapper.orderWxDelete(orderId);
    }

    @Override
    public void orderWxConfirm(OrderActionBO orderId) {
        orderMapper.orderWxConfirm(orderId);
    }

    @Override
    public OrderGoods orderGoods(Integer orderId, Integer goodsId) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        return orderGoodsList.get(0);
    }

    @Transactional
    @Override
    public void orderComment(OrderCommentBO orderCommentBO) {
        orderGoodsMapper.orderComment(orderCommentBO.getOrderGoodsId());
        Integer orderId = orderGoodsMapper.orderCommentGetOrderId(orderCommentBO.getOrderGoodsId());
        orderMapper.orderComment(orderId);
        Integer goodsId = orderGoodsMapper.orderCommentGetGoodsId(orderCommentBO.getOrderGoodsId());
        DateTime time = DateTime.now();

        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        Integer id = user.getId();
        byte type = 0;
        boolean hasPicture = false;
        if (orderCommentBO.getPicUrls().length != 0) hasPicture = true;

        Comment comment = Comment.builder().valueId(goodsId)
                .type(type)
                .content(orderCommentBO.getContent())
                .userId(id)
                .hasPicture(hasPicture)
                .picUrls(orderCommentBO.getPicUrls())
                .star(orderCommentBO.getStat())
                .addTime(time)
                .updateTime(time)
                .build();

        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        commentMapper.insertSelective(comment);
    }

    @Override
    //下单
    public OrderGoods orderSubmit(OrderSubmitBo orderSubmitBo) {
        OrderGoods orderGoods1 = new OrderGoods();
        Date now = new Date();
        int cartId = orderSubmitBo.getCartId();
        int addressId = orderSubmitBo.getAddressId();
        int grouponRulesId = orderSubmitBo.getGrouponRulesId();
        String message = orderSubmitBo.getMessage();
        int couponId = orderSubmitBo.getCouponId();
        Order order = new Order();
        String orderSn = OrderUtils.getOrderSn();
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //创建订单对象
        order.setUserId(user.getId());
        order.setOrderSn(orderSn);
        order.setOrderStatus((short) 101);
        //查询地址
        Address address = addressMapper.selectByPrimaryKey(addressId);
        order.setConsignee(address.getName());
        order.setMobile(address.getMobile());
        order.setAddress(address.getAddress());
        order.setMessage(message);
        //查询商品总费用,调用购物车结算接口
        CartCheckoutVo cartCheckoutVo = cartService.queryCartCheckoutVo(new CartCheckOutBo(0, addressId, couponId, grouponRulesId));
        order.setGoodsPrice(cartCheckoutVo.getGoodsTotalPrice());
        order.setFreightPrice(cartCheckoutVo.getFreightPrice());
        order.setCouponPrice(cartCheckoutVo.getCouponPrice());
        order.setGrouponPrice(cartCheckoutVo.getGrouponPrice());
        order.setOrderPrice(cartCheckoutVo.getOrderTotalPrice());
        order.setActualPrice(cartCheckoutVo.getActualPrice());
        order.setIntegralPrice(new BigDecimal(0));
        order.setAddTime(now);
        order.setUpdateTime(now);
        //新增订单
        int insertOrder = orderMapper.insertSelective(order);
        if(insertOrder == 0) return null;
        int orderId = orderMapper.selectKey();
        //新增orderGoods
        List<Cart> checkedGoodsList = cartCheckoutVo.getCheckedGoodsList();

        for (Cart cart : checkedGoodsList) {
            //判断库存是否够
            Integer number = Integer.parseInt(cart.getNumber()+"");
            GoodsProduct product = goodsProductMapper.selectByPrimaryKey(cart.getProductId());
            if(number > product.getNumber()) return null;//库存不足
            OrderGoods orderGoods = new OrderGoods(null,orderId,cart.getGoodsId(),cart.getGoodsName()
                    ,cart.getGoodsSn(),cart.getProductId(),number,cart.getPrice(),cart.getSpecifications()
                    ,cart.getPicUrl(),null,now,now,false);
            int insertOrderGoodsRow = orderGoodsMapper.insertSelective(orderGoods);
            if(insertOrderGoodsRow == 0) return null;
            //将购物车的数据清除
            cart.setDeleted(true);
            int updateCart = cartMapper.updateByPrimaryKeySelective(cart);
            if(updateCart == 0) return null;
        }
        //将用户对应的优惠券销毁
        CouponUserExample couponUserExample = new CouponUserExample();
        couponUserExample.createCriteria().andDeletedEqualTo(false).andCouponIdEqualTo(couponId).andUserIdEqualTo(user.getId()).andStatusEqualTo((short) 0);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        if(couponUsers.size()>0){
            CouponUser couponUser = couponUsers.get(0);
            couponUser.setOrderId(orderId);
            couponUser.setStatus((short) 1);
            couponUser.setDeleted(false);
            couponUser.setUsedTime(now);
            couponUser.setUpdateTime(now);
            int updateCoupon = couponUserMapper.updateByPrimaryKeySelective(couponUser);
            if(updateCoupon == 0) return null;
        }
        orderGoods1.setOrderId(orderId);
        return orderGoods1;
    }

    @Override
    public Integer prepay(@RequestBody OrderGoods orderGoods) {
        Date now = new Date();
        Order updateOrder = orderMapper.selectByPrimaryKey(orderGoods.getOrderId());
        updateOrder.setOrderStatus((short) 201);
        String payId = OrderUtils.getPayId();
        updateOrder.setUpdateTime(now);
        updateOrder.setPayId(payId);
        updateOrder.setPayTime(now);
        int update = orderMapper.updateByPrimaryKey(updateOrder);
        if(update == 0) return 10000;
        return 0;
    }
}
